#include "ProxyServer.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include "../Stringops/StringOps.h"
using namespace std;

int buildClient(int argc, char*argv[]);

int main(int argc, char*argv[]){
	int mainRtn = 0;
	mainRtn = buildClient(argc, argv);
	if(mainRtn < 0) {
		exit(EXIT_FAILURE);	
	}
	return mainRtn;	
}

bool ipcheck(std::string _host) {
        std::vector<std::string> parts = split(_host, '.');
        for(unsigned int i = 0; i < parts.size(); i++)
                if(!is_numeric(parts[i]))
                        return false;
        return true;
}

int buildClient(int argc, char*argv[]){
	string _port;
	string _host;
	string _url;

	if(argc!=4){
		printf("correct command:<client> <server ip> <server port> <url to retrieve>\n");
		return 1;
	}else{
		_port = argv[2];
		_host = argv[1];
		_url = string(argv[3]);
		//_url = argv[3];
		if(ipcheck(_host) && is_numeric(_port)){
			ProxyConnection cliConn(_host, atoi(_port.c_str()));
			if(cliConn.sock == null) {
				// Failed to establish connection; terminate
				return -1;
			}
			std::string response = cliConn.send_url(_url);
			if(result < 0)
				return -1;
			printf("%s\n", response.c_str());
			cliConn.close_connection();		
		}else{
			printf("Ip and port is not right!\n");
			return 1;
		}
		return 0;
	}
	/*while(1){
		cout<<"please input the server ip address: ";
		getline(cin,_host);
		if(ipcheck(_host)==true){
			break;
		}else{			
			printf("It is not an ip format, please input again!\n");
			continue;
		}
	}
	cout<<"please input the server port: ";
	cin>>_port;	
	TCPConnection cliConn(_host, _port);
	for(;;){
		int _msgSize;
		char buffer[BUFFER_SIZE_CLI];
		cliConn.handle_client_connection();
	}
	cliConn.close_connection();*/
	return 0;
}
